package cn.turboinfo.fuyang.api.domain.admin.usecase.consumer;

import cn.turboinfo.fuyang.api.domain.common.service.user.SysUserService;
import cn.turboinfo.fuyang.api.domain.common.service.user.UserTypeRelService;
import cn.turboinfo.fuyang.api.domain.common.usecase.AbstractUseCase;
import cn.turboinfo.fuyang.api.entity.admin.fo.cunsumer.ConsumerFO;
import cn.turboinfo.fuyang.api.entity.common.pojo.user.SysUser;
import cn.turboinfo.fuyang.api.entity.common.pojo.user.UserTypeRel;
import com.google.common.collect.Lists;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import net.sunshow.toolkit.core.qbean.api.request.QPage;
import net.sunshow.toolkit.core.qbean.api.request.QRequest;
import net.sunshow.toolkit.core.qbean.api.response.QResponse;
import net.sunshow.toolkit.core.qbean.helper.component.mapper.BeanMapper;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@RequiredArgsConstructor
@Component
public class ConsumerSearchUseCase extends AbstractUseCase<ConsumerSearchUseCase.InputData, ConsumerSearchUseCase.OutputData> {
    private final SysUserService sysUserService;

    private final UserTypeRelService userTypeRelService;

    @Override
    protected OutputData doAction(InputData inputData) {

        QResponse<UserTypeRel> response = userTypeRelService.findAll(inputData.request, inputData.getRequestPage());
        val userRelList = response.getPagedData();

        List<Long> userIdList = userRelList
                .stream()
                .map(UserTypeRel::getUserId)
                .collect(Collectors.toList());

        val userMapCollector = sysUserService.findByIdCollection(userIdList).stream().collect(Collectors.toMap(SysUser::getId, Function.identity()));

        List<ConsumerFO> foList = Lists.newArrayList();
        for (UserTypeRel userRel : userRelList) {
            if (userMapCollector.containsKey(userRel.getUserId())) {
                ConsumerFO consumerFO = BeanMapper.map(userMapCollector.get(userRel.getUserId()), ConsumerFO.class);
                foList.add(consumerFO);
            }
        }
        QResponse<ConsumerFO> foResponse = new QResponse<>(response.getPage(), response.getPageSize(), foList, response.getTotal());

        return OutputData.builder()
                .qResponse(foResponse)
                .build();
    }

    @Getter
    @Setter
    @Builder
    public static class InputData extends AbstractUseCase.InputData {
        private QRequest request;

        private QPage requestPage;
    }

    @Getter
    @Setter
    @Builder
    public static class OutputData extends AbstractUseCase.OutputData {
        private QResponse<ConsumerFO> qResponse;
    }
}
